package com.keste.portal.ui.bean;


import com.keste.portal.ui.util.ADFUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import oracle.adf.controller.ControllerContext;
import oracle.adf.controller.TaskFlowContext;
import oracle.adf.controller.TaskFlowTrainModel;
import oracle.adf.controller.TaskFlowTrainStopModel;
import oracle.adf.controller.ViewPortContext;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;
import oracle.adf.view.rich.component.rich.layout.RichPanelHeader;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import oracle.jbo.Row;

public class EmployeeBean {
    private String trainStopImage;
    private RichInputText addressLine1Bind;
    private RichPanelFormLayout eduPanalFormBind;
    private boolean checkFlag = false;
    private int EmpId;
    private int count = 0;
    Map currentAddrOldValuesMap = new HashMap();
    Map educationMap = new HashMap();
    private RichPanelHeader currentAddressPanelHeader;

    public EmployeeBean() {
    }

    public void setEduPanalFormBind(RichPanelFormLayout eduPanalFormBind) {
        this.eduPanalFormBind = eduPanalFormBind;
    }

    public RichPanelFormLayout getEduPanalFormBind() {
        return eduPanalFormBind;
    }

    public void setAddressLine1Bind(RichInputText addressLine1Bind) {
        this.addressLine1Bind = addressLine1Bind;
    }

    public RichInputText getAddressLine1Bind() {
        return addressLine1Bind;
    }

    public void setEmpId(int EmpId) {
        this.EmpId = EmpId;
    }

    public int getEmpId() {
        this.EmpId = -1;
        return EmpId;
    }

    public boolean isCurrentTab() {
        //get access to the JSF context classes
        FacesContext fctx = FacesContext.getCurrentInstance();
        ELContext elctx = fctx.getELContext();
        Application app = fctx.getApplication();
        ExpressionFactory expressionFactory = app.getExpressionFactory();
        //trainNode is the name of the variable attribute defined in af:navigationPane
        ValueExpression ve =
            expressionFactory.createValueExpression(elctx, "#{node}",
                                                    Object.class);
        //get the rendered stop's viewActivity
        TaskFlowTrainStopModel renderedTrainNode =
            (TaskFlowTrainStopModel)ve.getValue(elctx);
        //get current train stop to cpmpare it with the current "rendered" train stop
        ControllerContext controllerContext = ControllerContext.getInstance();
        ViewPortContext currentViewPortCtx =
            controllerContext.getCurrentViewPort();
        TaskFlowContext taskFlowCtx = currentViewPortCtx.getTaskFlowContext();
        TaskFlowTrainModel taskFlowTrainModel =
            taskFlowCtx.getTaskFlowTrainModel();
        //the train stop that is rendered in the train bar
        String renderedActivityId = renderedTrainNode.getLocalActivityId();
        //the train's current stop: the state
        TaskFlowTrainStopModel currentStop =
            taskFlowTrainModel.getCurrentStop();

        if (renderedActivityId.equalsIgnoreCase(currentStop.getLocalActivityId())) {
            return true;
        }
        return false;
    }

    public void setTrainStopImage(String trainStopImage) {
        this.trainStopImage = trainStopImage;
    }

    public String getTrainStopImage() {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ELContext elctx = fctx.getELContext();
        Application app = fctx.getApplication();
        ExpressionFactory expressionFactory = app.getExpressionFactory();
        ValueExpression ve =
            expressionFactory.createValueExpression(elctx, "#{trainNode}",
                                                    Object.class);
        TaskFlowTrainStopModel renderedTrainNode =
            (TaskFlowTrainStopModel)ve.getValue(elctx);
        String renderedActivityId = renderedTrainNode.getLocalActivityId();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" +
                           renderedActivityId);
        //trainStopImage = "/images/" + renderedActivityId + ".png";
        trainStopImage = renderedActivityId;
        //return trainStopImage;
        return renderedActivityId;
    }

    public void onCheckCurrent(ValueChangeEvent vce) {
        checkFlag = (Boolean)vce.getNewValue();
        count++;
        BindingContainer bindings = getBindings();
        OperationBinding operationBinding =
            bindings.getOperationBinding("onCheckAction");
        operationBinding.getParamsMap().put("checkFlag", checkFlag);
        operationBinding.getParamsMap().put("count", count);
        operationBinding.execute();
        checkFlag = false;
        if (!operationBinding.getErrors().isEmpty()) {
            return;
        }
        AdfFacesContext.getCurrentInstance().addPartialTarget(getCurrentAddressPanelHeader());
    }


    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public void onEdit(ActionEvent actionEvent) {
        DCIteratorBinding educationIterator =
            ADFUtils.findIterator("EducationIterator");
        educationMap.put("DegreeName",
                         educationIterator.getCurrentRow().getAttribute("DegreeName"));
        educationMap.put("EmployeeId",
                         educationIterator.getCurrentRow().getAttribute("EmployeeId"));
        educationMap.put("Grade",
                         educationIterator.getCurrentRow().getAttribute("Grade"));
        educationMap.put("Specialization",
                         educationIterator.getCurrentRow().getAttribute("Specialization"));
        educationMap.put("University",
                         educationIterator.getCurrentRow().getAttribute("University"));
        educationMap.put("YearOfCompletion",
                         educationIterator.getCurrentRow().getAttribute("YearOfCompletion"));
    }

    public void onCancel(ActionEvent actionEvent) {
        DCIteratorBinding educationIterator =
            ADFUtils.findIterator("EducationIterator");
        educationIterator.getCurrentRow().setAttribute("DegreeName",
                                                       educationMap.get("DegreeName"));
        educationIterator.getCurrentRow().setAttribute("EmployeeId",
                                                       educationMap.get("EmployeeId"));
        educationIterator.getCurrentRow().setAttribute("Grade",
                                                       educationMap.get("Grade"));
        educationIterator.getCurrentRow().setAttribute("Specialization",
                                                       educationMap.get("Specialization"));
        educationIterator.getCurrentRow().setAttribute("University",
                                                       educationMap.get("University"));
        educationIterator.getCurrentRow().setAttribute("YearOfCompletion",
                                                       educationMap.get("YearOfCompletion"));
    }

    public void setCurrentAddressPanelHeader(RichPanelHeader currentAddressPanelHeader) {
        this.currentAddressPanelHeader = currentAddressPanelHeader;
    }

    public RichPanelHeader getCurrentAddressPanelHeader() {
        return currentAddressPanelHeader;
    }

    public List employeeSearchSuggestedItems(String string) {
        BindingContext context = BindingContext.getCurrent();
        BindingContainer bc = context.getCurrentBindingsEntry();
        OperationBinding setEmpOperation =
            bc.getOperationBinding("getFilteredEmployees");
        Map params = setEmpOperation.getParamsMap();
        params.put("string", string);
        Row[] r = (Row[])setEmpOperation.execute();
        List<SelectItem> li = new ArrayList<SelectItem>();
        SelectItem si;
        String str = "";
        String name = "";
        for (int i = 0; i < r.length; i++) {
            str = "";
            name = "";
            if ((String)r[i].getAttribute("FirstName") != null) {
                str += (String)r[i].getAttribute("FirstName") + " ";
                name += (String)r[i].getAttribute("FirstName");
            }
            if ((String)r[i].getAttribute("MidName") != null) {
                str += (String)r[i].getAttribute("MidName") + " ";
                name += " " + (String)r[i].getAttribute("MidName");
            }
            if ((String)r[i].getAttribute("LastName") != null) {
                str += (String)r[i].getAttribute("LastName") + " ";
                name += " " + (String)r[i].getAttribute("LastName");
            }
            str += "| ";
            if ((String)r[i].getAttribute("EmployeeRole") != null)
                str += (String)r[i].getAttribute("EmployeeRole") + " | ";
            if ((String)r[i].getAttribute("EmailId") != null)
                str += (String)r[i].getAttribute("EmailId") + " | ";
            if ((String)r[i].getAttribute("Mobile") != null)
                str += (String)r[i].getAttribute("Mobile");

            si = new SelectItem(name, str);
            li.add(si);
        }
        return li;
    }

    public void searchActionListener(ActionEvent actionEvent) {
        int i;
        if ((String)ADFUtils.evaluateEL("#{bindings.EmployeeDetail.inputValue}") !=
            null) {
            String string =
                (String)ADFUtils.evaluateEL("#{bindings.EmployeeDetail.inputValue}");
            for (i = 0; i < string.length(); i++) {
                if (string.charAt(i) != ' ') {
                    break;
                }
            }
            if (i == string.length()) {
                employeeSearchSuggestedItems("");
            } else
                employeeSearchSuggestedItems(string);
        } else {
            employeeSearchSuggestedItems("");
        }
    }

    public void departmentIdValueChange(ValueChangeEvent valueChangeEvent) {
        if (valueChangeEvent.getNewValue() == null) {
            ADFUtils.setEL("#{bindings.DepartmentId.inputValue}", null);
        }
    }

    public void managerIdValueChange(ValueChangeEvent valueChangeEvent) {
        if (valueChangeEvent.getNewValue() == null) {
            ADFUtils.setEL("#{bindings.ManagerId.inputValue}", null);
        }
    }

    public void resetActionListener(ActionEvent actionEvent) {
        BindingContainer bc = getBindings();
        OperationBinding op = bc.getOperationBinding("Delete");
        op.execute();
        op = bc.getOperationBinding("CreateInsert");
        op.execute();
        BindingContext context = BindingContext.getCurrent();
        bc = context.getCurrentBindingsEntry();
        OperationBinding setEmpOperation =
            bc.getOperationBinding("onResetEmployeeSearch");
        setEmpOperation.execute();
    }

    public void employeeRoleCodeValueChange(ValueChangeEvent valueChangeEvent) {
        if (valueChangeEvent.getNewValue() == null) {
            ADFUtils.setEL("#{bindings.EmployeeRoleCode.inputValue}", null);
        }
    }
}
